<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { getQRKey, createQR, checkQRStatus } from '@/apis/login.js'
import { useUserInfoStore } from '@/stores/userInfoStore.js'
import { useCookieStore } from '@/stores/cookieStore.js'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

// pinia
const useUserInfo = useUserInfoStore()
const useCookie = useCookieStore()

// router
const router = useRouter()
const route = useRoute()



// 二维码登录
const qrCode = ref({})
const scanMessage = ref('等待扫描...')
const checkQRStatusTimer = ref(null)
const qrLogin = async () => {
  // 获取二维码 key
  const { data } = await getQRKey()
  const qrKey = data.data.unikey
  // 发送请求（二维码 key），并在页面中生成二维码（base64）
  const getQrimg = await createQR(qrKey)
  qrCode.value = getQrimg.data

  // 定时器，检测用户扫码状态
  checkQRStatusTimer.value = setInterval(async () => {
    const data = await checkQRStatus(qrKey)
    const code = data.data.code
    console.log(code);
    scanMessage.value = '等待扫描...'
    // 判断扫码状态；800 为二维码过期，801 为等待扫码，802 为待确认，803 为授权登录成功
    if (code === 800) {
      clearInterval(checkQRStatusTimer.value)
      qrCode.value = {}
      scanMessage.value = '二维码已失效，点击二维码重新获取'
    } else if (code === 802) {
      scanMessage.value = '授权中...'
    } else if (code === 803) {
      useCookie.cookie = data.data
      useUserInfo.getLoginStatus()
      ElMessage({
        type: 'success',
        message: '授权成功'
      })
      router.replace({
        path: route.query.redirect || '/'
      })
      clearInterval(checkQRStatusTimer.value)
    }
  }, 3000)
}

onMounted(() => qrLogin())
onBeforeUnmount(() => clearTimeout(checkQRStatusTimer.value))

</script>

<template>
  <h3 class="title">推荐使用网易云音乐 APP 扫码登录</h3>
  <div class="login-qr-container">
    <div class="qr-box">
      <img v-if="qrCode.data" :src="qrCode.data.qrimg">
      <img v-else src="@/assets/QR.png" @click="qrLogin()">
    </div>
  </div>
  <div class="tips">
    <p class="qrStatus">{{ scanMessage }}</p>
    <RouterLink to="/">返回首页</RouterLink>

  </div>
</template>

<style scoped lang='scss'>
.title {
  line-height: 70px;
  text-align: center;
}

.login-qr-container {
  display: flex;
  justify-content: center;

  .qr-box {
    height: 300px;
    width: 300px;
    animation: am1 2s;

    img {
      width: 100%;
      height: 100%;
      background-color: transparent;
    }

    @keyframes am1 {
      0% {
        opacity: 0;
      }

      100% {
        opacity: 1;
      }
    }
  }
}

.tips {
  width: 500px;
  text-align: center;

  .qrStatus {
    line-height: 80px;
    font-weight: bold;
    font-size: 16px;
  }

  a {
    cursor: pointer;
  }
}
</style>
